﻿using FineUI;
using SysManage.BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.Forum;
using ZHDJ.WebPage;

namespace SysManage.Module.Forum
{
    public partial class ForumEdit : PageBase
    {
        public List<PartyForumType> ListPartyForumType;

        public ForumEdit()
        {
            ListPartyForumType = new List<PartyForumType>();
        }

        #region 属性
        /// <summary>
        /// 菜单ID
        /// </summary>
        public string TID
        {
            get
            {
                return this.Request["ID"] ?? "";
            }
        }


        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        #region 数据操作

        public void BindData()
        {
            List<PartyForumType> dbPartyForumType = DB.PartyForumTypes.ToList();

            PartyForumType parent = new PartyForumType() { ID = "" };

            ResolveMenuCollection(dbPartyForumType, parent, 0);
            List<PartyForumType> mys = ResolveDDL<PartyForumType>(ListPartyForumType, "");
            // 绑定到下拉列表（启用模拟树功能和不可选择项功能）
            ddlTitleID.EnableSimulateTree = true;
            ddlTitleID.DataTextField = "Title";
            ddlTitleID.DataValueField = "ID";
            ddlTitleID.DataSimulateTreeLevelField = "TreeLevel";
            ddlTitleID.DataEnableSelectField = "Enabled";

            ddlTitleID.DataSource = mys;
            ddlTitleID.DataBind();
        }

        protected void LoadData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            string id = GetQueryIntValue("ID");

            if (!string.IsNullOrEmpty(id))
            {
                PartyForumType oModel = DB.PartyForumTypes.Find(id);

               
                if (oModel.ParentID != null)
                {
                    // 选中当前节点的父节点
                    ddlTitleID.SelectedValue = oModel.ParentID;
                }
                this.rbShowIndex.SelectedValue = oModel.IsShowIndex?"1":"0";
                this.txtOrderno.Text = oModel.OrderNo.ToString();
                ;
                this.txtTitle.Text = oModel.Title;
                this.txtDec.Text = oModel.Description;

                if (!string.IsNullOrEmpty(oModel.ImageUrl))
                {
                    this.hdImageId.Text = oModel.ImageUrl;
                    filePhoto.EmptyText = UpFileBusiness.GetFileName(hdImageId.Text);
                    imgPhoto.ImageUrl = UpFileBusiness.GetFileUrl(hdImageId.Text);
                }

                var Admindt = PartyForumTypeAdmin.GetTitleLoginID(TID);
                var titleAdminId = "";
                var titleAdminName = "";
                if (Admindt.Rows.Count > 0)
                {
                    for (int i = 0; i < Admindt.Rows.Count; i++)
                    {
                        titleAdminId += Convert.ToString(Admindt.Rows[i][0]) + ",";
                        titleAdminName += Convert.ToString(Admindt.Rows[i][1]) + ",";
                    }
                    titleAdminId = titleAdminId.Substring(0, titleAdminId.Length - 1);
                    titleAdminName = titleAdminName.Substring(0, titleAdminName.Length - 1);

                }
                ppAdmin.Value = titleAdminId;
                ppAdmin.Text = titleAdminName;
            }

        }




        private int ResolveMenuCollection(List<PartyForumType> dbType, PartyForumType parent, int level)
        {
            int count = 0;

            foreach (var item in dbType.Where(m => m.ParentID == parent.ID).OrderBy(a=>a.OrderNo))
            {
                count++;

                ListPartyForumType.Add(item);
                item.TreeLevel = level;
                item.IsTreeLeaf = true;
                item.Enabled = true;

                level++;
                int childCount = ResolveMenuCollection(dbType, item, level);
                if (childCount != 0)
                {
                    item.IsTreeLeaf = false;
                }
                level--;
            }

            return count;
        }
        protected void SaveData()
        {
            string id = GetQueryIntValue("id");
            PartyForumType forumType = null;

            if (id != "")
            {
                forumType = DB.PartyForumTypes.Find(id);
                if (forumType == null)
                {
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
            }
            else
            {

                forumType = new PartyForumType();
                forumType.ID = StringHelper.NewID;
                DB.PartyForumTypes.Add(forumType);
            }

            forumType.Title = txtTitle.Text.Trim();
            forumType.Description = txtDec.Text.Trim();
            forumType.ImageUrl = this.hdImageId.Text;
            forumType.ParentID = this.ddlTitleID.SelectedValue=="-1"?"": this.ddlTitleID.SelectedValue;
            forumType.IsShowIndex = this.rbShowIndex.SelectedValue=="1";
            forumType.OrderNo = Convert.ToInt32( txtOrderno.Text);
            DB.SaveChanges();

            if (!string.IsNullOrEmpty(ppAdmin.Value))
            {
                DB.PartyForumTypeAdmins.Where(t => t.TypeID == forumType.ID).ToList().ForEach(t => DB.PartyForumTypeAdmins.Remove(t));

                PartyForumTypeAdmin admin = null;
                foreach (string item in ppAdmin.Value.Split(','))
                {
                    admin = new PartyForumTypeAdmin();
                    admin.ID = StringHelper.NewID;
                    admin.TypeID = forumType.ID;
                    admin.LoginID = item;

                    DB.PartyForumTypeAdmins.Add(admin);

                    DB.SaveChanges();
                }
            }

            if (DB.PartyForumTypeAdmins.Where(t => t.TypeID == forumType.ID && t.LoginID == "admin").Count() == 0)
            {
                PartyForumTypeAdmin admin = new PartyForumTypeAdmin();
                admin.ID = StringHelper.NewID;
                admin.TypeID = forumType.ID;
                admin.LoginID = "admin";

                DB.PartyForumTypeAdmins.Add(admin);

                DB.SaveChanges();
            }
        }

        #endregion

        #region 事件

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData();

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID, "论坛版块图标", SysEnum.UploadFileType.uploadimage);
            if (rs.IsSuccess)
            {
                hdImageId.Text = rs.FileID;
                imgPhoto.ImageUrl = "~/" + rs.FileUrl;
                imgPhoto.ImageWidth = Unit.Pixel(300);

                PageContext.RegisterStartupScript("ReDoLayout();");
            }
            else
            {
                Alert.Show("上传失败！" + rs.Message, String.Empty);
            }
        }
    }
}